package com.sdx.console.base.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.system.service.DictBusinessService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.base.entity.*;
import com.sdx.console.base.service.*;
import com.sdx.console.base.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 消息管理 接口
 */
@RequestMapping("/base/baseMessage")
@Controller
public class BaseMessageController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(BaseMessageController.class);
    private static final String MODEL = "/base/baseMessage";


    @Resource
	private BaseMessageService baseMessageService;

	@Resource
	private ResCloudFileService resCloudFileService;

	@Resource
	private DictBusinessService dictBusinessService;

	@Resource
	private BaseDataService baseDataService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		List<DictBusiness> moduleList = dictBusinessService.getModule();
		view.addObject("moduleList",moduleList);
		view.addObject("moduleJson",JSON.toJSONString(moduleList));
		view.addObject("provinceList",baseDataService.getAllProvince());
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("base.baseMessage.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("base.baseMessage.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Long messageId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        BaseMessage baseMessage = baseMessageService.queryById(messageId);
        view.addObject("baseMessage", baseMessage);
		baseMessage.setModule(baseMessage.getModule()+",");
		setPageParam(view,request);
		try {
			view.addObject("baseMessageJson", JacksonUtils.toJsonString(baseMessage,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("base.baseMessage.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("base.baseMessage.query")
    @ResponseBody
    public JsonResult<PageQuery> list(BaseMessage condtion)
    {
        PageQuery page = condtion.getPageQuery();
        baseMessageService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,BaseMessage baseMessage,HttpServletRequest request,MultipartFile imgFile) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(imgFile)) {
			try
			{
		        String imgFileNamePair = FileUtils.upload(subPath,imgFile);
		        String imgStoreFile = imgFileNamePair.split("::")[0];
		        imgStoreFile = subPath+imgStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+imgStoreFile,bucketName,imgStoreFile.substring(1));
				String imgUrl = "https://sdxcomm."+ConfigService.ossDomain+imgStoreFile;
				baseMessage.setImg(imgUrl);
				baseMessage.setModule(baseMessage.getModule()+",");
				//baseMessage.setChannelCode(",miniprogram,");
				resCloudFileService.insertResFile(ResCloudFile.ALI,imgStoreFile,imgUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}

		CoreUser user = getLoginUser(request);

    	if (isNew) {
			baseMessage.setSort(0);
			baseMessage.setCreatedBy(user.getId().intValue());
			baseMessage.setCreatedName(user.getName());
			baseMessage.setCreatedTime(new Date());
			baseMessage.setUpdatedBy(user.getId().intValue());
			baseMessage.setUpdatedName(user.getName());
			baseMessage.setUpdatedTime(new Date());
			baseMessageService.save(baseMessage);
		} else {
			baseMessage.setUpdatedBy(user.getId().intValue());
			baseMessage.setUpdatedName(user.getName());
			baseMessage.setUpdatedTime(new Date());
			baseMessageService.updateTemplate(baseMessage);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("base.baseMessage.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)BaseMessage baseMessage,HttpServletRequest request,
						  @RequestParam("imgFile") MultipartFile imgFile)
    {
        return save(true,baseMessage,request,imgFile);
    }

    @PostMapping("/update.json")
    @Function("base.baseMessage.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  BaseMessage baseMessage,HttpServletRequest request,
									 @RequestParam("imgFile") MultipartFile imgFile) {
		//baseMessage.setChannelCode(",miniprogram,");
		return save(false,baseMessage,request
		,imgFile
		);
    }
   
    @GetMapping("/view.json")
    @Function("base.baseMessage.query")
    @ResponseBody
    public JsonResult<BaseMessage>queryInfo(Long messageId) {
        BaseMessage baseMessage = baseMessageService.queryById( messageId);
        return  JsonResult.success(baseMessage);
    }

    @PostMapping("/delete.json")
    @Function("base.baseMessage.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        baseMessageService.batchDelBaseMessage(idList);
        return JsonResult.success();
    }

	@PostMapping("/setTop.json")
	@ResponseBody
	public JsonResult setTop(String ids,Integer sort,HttpServletRequest request) {
		List<String> idList = Utils.strToList(ids,",");
		CoreUser user = getLoginUser(request);
		BaseMessage baseMessage = new BaseMessage();
		baseMessage.setSort(sort);
		baseMessage.setUpdatedBy(user.getId().intValue());
		baseMessage.setUpdatedName(user.getName());
		baseMessage.setUpdatedTime(new Date());
		baseMessageService.setTop(idList,baseMessage);
		return JsonResult.success();
	}
    

}
